package com.hhoss.util.thread;

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadFactory implements java.util.concurrent.ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(11);
    private final AtomicInteger threadNumber = new AtomicInteger(11);
    private final ThreadGroup groups;
    private final String prefix;
    
    /**
     *  using default thread name: pool%d-work, name is pool%d-work%d. 
     *  jdk default Name : "pool-%d-thread-%d"
     */
    public ThreadFactory() {
    	this("pool%d-work");
    }

    /**
     * 
     * @param pattern the thread name prefix pattern, the thread name will be {pattern}%d = {pattern}342
     */
    protected ThreadFactory(String pattern) {
        SecurityManager s = System.getSecurityManager();
        groups = (s != null) ? s.getThreadGroup() :  Thread.currentThread().getThreadGroup();
        prefix = String.format(pattern,poolNumber.getAndIncrement());
        // "pool-" +poolNumber.getAndIncrement() + "-thread-";
    }
    
    /**
     * @return the pool prefix name
     */
    public String getPrefix(){
    	return prefix;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(groups, r, prefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()){
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY){
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
